package com.jiangxjsy.crm.service.impl;

import com.jiangxjsy.core.constant.BasicConstant;
import com.jiangxjsy.core.enums.FieldEnum;
import com.jiangxjsy.core.exception.AuthorizationException;
import com.jiangxjsy.core.jwt.JwtCore;
import com.jiangxjsy.core.wrap.ResultCode;
import com.jiangxjsy.crm.mapper.CrmFieldMapper;
import com.jiangxjsy.crm.property.JwtProperty;
import com.jiangxjsy.crm.service.CrmFieldService;
import com.jiangxjsy.crm.service.CrmFieldSortService;
import com.jiangxjsy.crm.service.CrmRoleFieldService;
import com.jiangxjsy.crm.support.AdminUserSupport;
import com.jiangxjsy.crm.support.CrmFieldSupport;
import com.jiangxjsy.model.core.entity.UserMeta;
import com.jiangxjsy.model.crm.bo.CrmFieldBO;
import com.jiangxjsy.model.crm.entity.CrmField;
import com.jiangxjsy.model.crm.vo.CrmFieldSortVO;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * wukong-crm-master
 * 蒋胜宇
 * 2025/6/18 16:13
 */

@Service
public class CrmFieldServiceImpl implements CrmFieldService {
    @Resource
    private CrmFieldMapper crmFieldMapper;

    @Resource
    private CrmFieldSortService crmFieldSortService;

    @Resource
    private CrmRoleFieldService crmRoleFieldService;

    @Resource
    private CrmFieldSupport crmFieldSupport;

    @Resource
    private AdminUserSupport adminUserSupport;

    @Resource
    private JwtProperty jwtProperty;

    /**
     * 查询模块字段列表
     *
     * @param label 模块标识
     * @param request 请求
     * @param response 响应
     * @return 模块字段列表
     */
    @Override
    public List<CrmFieldSortVO> queryListHead(Integer label, HttpServletRequest request, HttpServletResponse response) {
        String token = request.getHeader(BasicConstant.TOKEN_NAME);
        UserMeta userMeta;
        try {
            userMeta = new JwtCore<>(UserMeta.class).analyzeToken(token, jwtProperty.getPublicKey());
        } catch (IllegalAccessException | NoSuchMethodException | InvocationTargetException | InstantiationException e) {
            throw new AuthorizationException(ResultCode.AuthorizationResultCode.AUTHORIZATION_LOGIN_ERR);
        }
        Long userId = userMeta.getUserId();

        List<CrmFieldSortVO> fieldSortVOList = crmFieldSortService.queryListHead(label, userId);
        if (!adminUserSupport.isAdmin(token, userId)) {
            List<String> list = crmRoleFieldService.queryNoAuthField(label, token);
            List<String> fieldList = list.stream().map(fieldName -> {
                if ("businessId".equals(fieldName)) {
                    return "businessName";
                } else if ("companyUserId".equals(fieldName)) {
                    return "companyUserName";
                } else if ("contactsId".equals(fieldName)) {
                    return "contactsName";
                } else if ("customerId".equals(fieldName)) {
                    return "customerName";
                } else if ("receivablesPlanId".equals(fieldName)) {
                    return "planNum";
                } else if ("contractId".equals(fieldName)) {
                    return "contractNum";
                } else if ("ownerUserId".equals(fieldName)) {
                    return "ownerUserName";
                } else {
                    return fieldName;
                }
            }).collect(Collectors.toList());
            fieldSortVOList.removeIf(field -> fieldList.contains(field.getFieldName()));
        }

        fieldSortVOList.forEach(fieldSort -> {
            if ("website".equals(fieldSort.getFieldName())) {
                fieldSort.setFormType(FieldEnum.WEBSITE.getFormType());
            }else {
                fieldSort.setFormType(FieldEnum.parse(fieldSort.getType()).getFormType());
            }
        });

        fieldSortVOList.removeIf(fieldSort -> crmFieldSupport.equalsByType(
                fieldSort.getType(), FieldEnum.DESC_TEXT, FieldEnum.DETAIL_TABLE)
        );
        return fieldSortVOList;
    }

    /**
     * 查询自定义字段列表
     *
     * @param label 模块标识
     * @param isQueryHide 是否查询隐藏字段
     * @return 自定义字段列表
     */
    @Override
    public List<CrmFieldBO> list(Integer label, boolean isQueryHide) {
        List<CrmField> crmFieldList = crmFieldMapper.selectFieldsByLabelAndHidden(label, isQueryHide);
        List<CrmFieldBO> fieldList = new ArrayList<>();
        for (CrmField crmField : crmFieldList) {
            CrmFieldBO crmFieldBO = new CrmFieldBO();
            BeanUtils.copyProperties(crmField, crmFieldBO);
            fieldList.add(crmFieldBO);
        }

        fieldList.forEach(field -> crmFieldSupport.recordToFormType2(
                field, FieldEnum.parse(Math.toIntExact(field.getType())))
        );
        return fieldList;
    }

    /**
     * 查询隐藏字段
     *
     * @param label 模块标识
     * @return 隐藏字段
     */
    @Override
    public List<CrmField> queryHiddenFieldNamesByLabel(Integer label) {
        return crmFieldMapper.selectHiddenFieldNamesByLabel(label);
    }

    /**
     * 根据模块标识和字段类型查询字段
     *
     * @param label 模块标识
     * @param descTextType 字段类型
     * @return 字段列表
     */
    @Override
    public List<CrmField> queryCrmFieldsByLabelAndType(Integer label, Integer descTextType) {
        return crmFieldMapper.selectCrmFieldsByLabelAndType(label, descTextType);
    }
}
